import cv2
import numpy as np

img = cv2.imread('./m.png')

img2 = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 二值化古籍黑白化

#ret,dts = cv2.threshold(img2,140,255,cv2.THRESH_BINARY)
ret,thresh = cv2.threshold(img2,0,255,cv2.THRESH_BINARY + cv2.THRESH_OTSU) #自动设置颜色范围
# kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
# dst = cv2.dilate(dts,kernel=kernel,iterations=1)

kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
sure_bg = cv2.dilate(opening, kernel, iterations=1)
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
_, sure_fg = cv2.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)

_, background = cv2.threshold(dist_transform, 0.7 * dist_transform.max(), 255, cv2.THRESH_BINARY)
background = np.uint8(background)

mask = cv2.add(sure_fg, background)

res = cv2.bitwise_and(img, img, mask=mask)

cv2.namedWindow('dts',cv2.WINDOW_FREERATIO)
cv2.imshow('dist_transform',dist_transform)
cv2.imshow('img2',img2)
cv2.imshow('res',res)

#cv2.imwrite('m2.jpg', dts)
cv2.waitKey(0)